if (window.plus) {
    ready();
} else {
    document.addEventListener('plusready', ready, false);
}

$(function(){
  if(AGENT_CLIENT.WEB){
    ready();
  } 
})

function ready() {
    
    var _user;																		//用户信息
    var mainorderno = getUrlParam("mainorderno");	//请求条件
    var requestUrl = "";
    var html = [];									//html字符串
    var _thisPage;									//当前页
    var orderDetailPage = function () {
        this.init();
    };
    orderDetailPage.prototype = {
        init: function () {
            this.loadData();
            this.bindEvent();
        },
        //加载数据
        loadData: function () {
          _user = getLocalStorage(STORAGE_MANAGER.user);
          if (!_user) {
            redirect("../account/login.html");
            return false;
          }
          if (!mainorderno) {
            $.toast("订单号为空");
            return false;
          }else{
            this.loadOrder();
          }
        },
        //请求订单数据
        loadOrder: function () {
          requestUrl = CONFIG_MANAGER.RequstUrl + "v1/orders/main/" + mainorderno + "/" + _user.id;
          $.ajax({
            type: "GET",
            url: requestUrl,
            async: true,
            headers: { "token": _user.token },
            beforeSend: function () { $.showWaiting("等待中"); }
          }).done(function (data) {
            setTimeout(function () {
                $.closeWaiting();
            }, 500);
            _thisPage.loadOrderDetail(data);
          });
        },
        //加载订单详情
        loadOrderDetail: function (orders) {
            html = [];
            var coinTotal = 0;
            var totalDiscountfee = 0;
            var totalPayfee = 0;
            var order = orders[0];
            //商品信息
            html.push('<div class="ddhbg">');
            html.push('<p class="ddh"><span>订单号：' + order.main_order_no + '</span>'+ order.status_text +'</p>');
            html.push('</div>');

            html.push('<div class="shdzbg">');            
            //收货信息
            html.push('<p class="shxxbt">收货信息</p>');
            html.push('<div class="shdzbg">');
            html.push('<div class="shdzk mbtopbottom">');
            html.push('<p class="dwei"><img src="../../images/ditutb.png"/></p>');
            html.push('<div class="shdzhi">');
            html.push('<p class="sjrmc"><span>' + (order.mobile||'') + '</span>收件人：' + (order.consignee||'') + '</p>');
            html.push('<p>'+ (order.region_name||'') + (order.address||'') + '</p>');
            html.push('<p><span>发票：' + (order.invoice_title||'') + '</span>备注：' + (order.remark||'') + '</p>');
            html.push('</div>');
            html.push('</div>');
            html.push('</div>');
            //物流信息
            html.push('<div class="wlxqbg">');
            html.push('<p class="shxxbt">物流详情</p>');
            html.push('<div class="wlxqnrbg mbtopbottom">');
            html.push('<p class="wlxqnr mbbottom"><span>'+ (order.delivery_type_text||'') +'</span>物流方法</p>');
            html.push('<p class="wlxqnr mbbottom"><span>'+ (order.express_name||'') +'</span>物流公司</p>');
            html.push('<p class="wlxqnr mbbottom"><span>'+ (order.express_code||'') +'</span>运单号码</p>');
            html.push('<p name="orderOps" tip="" class="wlxqnr"><span>');
            if(order.logs.length>0){
              //2015-8-20  8:30:20  到达杭州市西湖区
              html.push( toDateString(order.logs[0].create_time, 'yyyy-MM-dd hh:mm') + order.logs[0].record );
            }
            html.push('<b class="icon-right">></b></span>');
            html.push('物流信息</p>');
            html.push('</div>');
            html.push('</div>');
            
            
            $.each(orders, function(i, order) {	            
	            //店铺
	            html.push('<div class="wlxqbg">');
	            html.push('<div class="wlxqnrbg mbtopbottom" style="border-top: 0px;">');
	            
	            $.each(order.items, function (i, goods) {
	              html.push('<p class="shxxbt1  mbbottom"><span>'+ goods.shop_name +'</span></p>');
	              html.push('<div class="mbbottom with100 overflow">');
	              html.push('<dl class="cpxqxztop cpxqxztop1 mtop0">');
	              html.push('<dt><img src="'+ getImageUrl(goods.logo,65,66) +'" /></dt>');
	              html.push('<dd>');
	              html.push('<p class="floatr">');
	              //星币
	              html.push('<span class="money">&yen;' + goods.act_price + '</span>');
	              html.push('+');
	              html.push('<span class="jinbi"><b><img src="../../images/jbtub.jpg"></b>'+ goods.coin +'</span>');
	              html.push('</p>' + goods.sku_name);
	              html.push('</dd>');
	              html.push('<dd class="huisezi"><span class="x2">x'+ goods.qty +'</span>' + goods.specs + '</dd>');
	              html.push('</dl>');
	              html.push('</div>');
	            });	
	            html.push('<p class="wlxqnr mbbottom"><span style="margin-right:0px">&yen;' + order.goods_fee + '+<span class="jinbi huangzi"><b><img src="../../images/jbtub.jpg">'+ order.ttl_coin +'</b></span></span>小计</p>');
	            html.push('<p class="wlxqnr mbbottom"><span>&yen;' + order.delivery_fee + '</span>运费</p>');
	            html.push('</div>');
	            html.push('</div>');
	            coinTotal +=  order.ttl_coin;
	            totalDiscountfee +=  order.discount_fee;
	            totalPayfee += order.pay_fee;
            });
            
            //总计
            html.push('<div class="wlxqbg">');
            html.push('<div class="wlxqnrbg mbtopbottom" style="border-top: 0px;">');
            html.push('<p class="wlxqnr mbbottom"><span class="jinbi huangzi"><b><img src="../../images/jbtub.jpg"></b>'+ coinTotal +'</span>星币</p>');
            html.push('<p class="wlxqnr mbbottom"><span>&yen;' + totalDiscountfee + '</span>优惠</p>');
            html.push('<p class="wlxqnr"><span class="hongzei">&yen;' + totalPayfee + '</span>实付</p>');            
            html.push('</div>');
            html.push('</div>');
            
            //下单时间
            html.push('<p class="xdshijian"><span>下单时间:</span>' + toDateString(order.create_time, 'yyyy-MM-dd hh:mm') + '</p>');
            html.push('<p class="xdshijian"><span>付款时间:</span>' + toDateString(order.pay_time, 'yyyy-MM-dd hh:mm') + '</p>');
            
            html.push('<p class="xdshijian"><span>发货时间:</span>');
            //发货时间 2015-8-20  17:29:01
            if( order.status >= 6 && order.logs.length>0 ){
              html.push( toDateString(order.logs[0].create_time, 'yyyy-MM-dd hh:mm') );
            }
            html.push('</p>');
            html.push('</div>');
            $("#orderDetail").html(html.join(''));
            //订单操作
            var opsHtml = [];
            opsHtml.push('<div class="footbg1 mbtopbottom">');
            opsHtml.push('<p class="anniu-box">');
            var operations = getOrderOperation(order.status);
            
            $.each(operations, function(i,item) {
              var orderItem = {"ops":item.key, "id":order.id}
              opsHtml.push('<span name="orderOps" tip='+ JSON.stringify(orderItem) +' class="anniu ');
              if('cancel' == item.key){
              	opsHtml.push('huangsebg_gray');
              }
              opsHtml.push('">');
              opsHtml.push('<a href="javascript:void(0);">');
              opsHtml.push(item.text);
              opsHtml.push('</a></span>');
            });
            opsHtml.push('</p>');
            opsHtml.push('</div>');
            $("#orderDetail").after(opsHtml.join(''));
        },
        //页面事件
        bindEvent: function () {
			 //回退
			 $("#back").on("click", function(){
			    if(AGENT_CLIENT.APP){
			    	plus.webview.currentWebview().close();
			    }else{
			    	back();
			    }
			});
          
          //滚动到底部显示向上图标
          $("#orderDetail").scroll(function () {
              var divHeight = $(this).height(), scrollTop = $(this)[0].scrollTop, scrollHeight = $(this)[0].scrollHeight;
              var paddingBottom = parseInt($(this).css('padding-bottom')), paddingTop = parseInt($(this).css('padding-top'));
              //console.log("divHeight:"+divHeight+"  scrollTop:"+scrollTop+" paddingBottom:"+paddingBottom+" paddingTop:"+paddingTop+" scrollHeight:"+scrollHeight);
              if ((divHeight + scrollTop + paddingBottom + paddingTop) >= scrollHeight) {
                  $("#gotop").show();
              } else {
                  $("#gotop").hide();
              }
          });

          //点击向上图标
          $("#gotop").on("click", function () {
              $('#orderDetail').animate({scrollTop: '0px'}, 400);
          });
          
          //订单操作
          $("body").on("click", "span[name='orderOps']", function(){
          	var thisModel = this;
            var orderItem = JSON.parse( $(this).attr("tip") );
            var redirectUrl = '';
            operateOrder(orderItem);
						switch (orderItem.ops){
							case 'cancel':
								redirectUrl = 'orders.html?type=cancel';
								break;
							case 'confirmDelivery':
								redirectUrl = 'orders.html?type=finish';
								break;
							default:
								break;
						}
						if(redirectUrl != ''){
							redirect(redirectUrl);
						}
          });
        },

        // 添加扫描历史纪录
        addBarcodeHistory: function (data) {
            var barcodehistory = getLocalStorage(STORAGE_MANAGER.barcodehistory);
            if (!barcodehistory) {
                barcodehistory = [];
            }
            barcodehistory.push({
                type: 3,
                result: _goodsId,
                desc: data.name + data.specs + data.title,
                create_time: new Date().getTime()
            });

            setLocalStorage(STORAGE_MANAGER.barcodehistory, barcodehistory);
        }
    };
    _thisPage = new orderDetailPage();
}